package com.example.demo.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class CaptchaUtil {
    private static final int WIDTH = 100;
    private static final int HEIGHT = 40;
    private static final String CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final Random RANDOM = new Random();

    // 生成验证码图片并返回Base64字符串和验证码文本
    public static Map<String, String> generateCaptcha() {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        
        // 设置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);
        
        // 生成随机验证码
        StringBuilder captchaText = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            captchaText.append(CHARS.charAt(RANDOM.nextInt(CHARS.length())));
        }
        
        // 绘制验证码
        g.setColor(Color.GREEN);
        g.setFont(new Font("Arial", Font.BOLD, 20));
        g.drawString(captchaText.toString(), 20, 25);
        
        // 添加干扰线
        g.setColor(Color.GRAY);
        for (int i = 0; i < 5; i++) {
            int x1 = RANDOM.nextInt(WIDTH);
            int y1 = RANDOM.nextInt(HEIGHT);
            int x2 = RANDOM.nextInt(WIDTH);
            int y2 = RANDOM.nextInt(HEIGHT);
            g.drawLine(x1, y1, x2, y2);
        }
        
        g.dispose();
        
        // 转换为Base64
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "png", baos);
            String base64Image = Base64.getEncoder().encodeToString(baos.toByteArray());
            Map<String, String> result = new HashMap<>();
            result.put("captchaImage", "data:image/png;base64," + base64Image);
            result.put("captchaText", captchaText.toString());
            return result;
        } catch (Exception e) {
            throw new RuntimeException("生成验证码失败", e);
        }
    }
}